import store from '@/store/index.js'
export default class Zsockets {
	constructor() {}

	connets() {
		const user = uni.getStorageSync('user');
		uni.showLoading({
			title: "正在连接中~"
		});
		return new Promise(resolve => {
			uni.connectSocket({
				url: "ws://127.0.0.1:3000/conectWs?user=" + user.name,
				success: (e) => {
					uni.onSocketMessage((e) => {
						console.log("server信息：", e);
						const pages = getCurrentPages();
						const data = JSON.parse(e.data);
						const page = pages[pages.length - 1].$vm;
						// console.log(page);
						console.log(data);
						switch (data.type) {
							case 'login':
								page.uploadUserList(data);
								break;
							case 'say':
								page.uploadMsgList(data);
								break;
						}
					});
				},
				fail: (err) => {
					console.log(err);
				},
				complete: () => {
					uni.hideLoading();
				}
			});
			uni.onSocketOpen((res) => {
				console.log('WebSocket连接已打开！');
				store.commit('changeSocketSta', 1);
				resolve();
				uni.showToast({
					title: "连接已恢复！",
					icon: "none"
				})
			});
		})


		uni.onSocketError(function(res) {
			console.log('WebSocket连接打开失败，请检查！');
		});

		uni.onSocketClose(res => {
			console.log('WebSocket 已关闭！');
			store.commit('changeSocketSta', 2);
			uni.showToast({
				title: "连接已断开！",
				icon: "none"
			})
		});

	};
	/**
	 * @param {Object} methodname 方法名
	 * @param {Object} data 数据
	 */
	sendMsg(methodname, data = {}) {
		data.methodname = methodname;
		data = JSON.stringify(data);
		return new Promise(resolve => {
			uni.sendSocketMessage({
				data: data,
				success: (e) => {
					resolve(e)
				},
				fail(err) {
					console.log(err);
				}
			});
		})

	};
	close() {
		try {
			return Promise(resolve => {
				uni.closeSocket({
					complete: () => {
						resolve()
					}
				})
			})
		} catch (e) {}
	}
}
